import {defineStore} from "pinia";
import service from "@/utils/useRequest";
import type {FormInstance, FormRules} from "element-plus";
import dayjs from "dayjs";
import {Random} from "mockjs";
import {showModal, toast} from "@/utils/useLayer";

export const useNoticeStore = defineStore(
    'notice',
    () => {
        //
        const noticeList = ref([])
        const isLoading = ref(false)

        // 分页
        const pageSize = 10
        const currentPage = ref(1)
        const totalCount = ref(0)
        const currentTableData = ref([])

        // 新增
        const addFormDialogRef = ref(null)
        const addFormModelRef = ref<FormInstance>()
        // 编辑
        const editFormDialogRef = ref(null)
        const editFormModelRef = ref<FormInstance>()

        const commonFormModel = ref({
            title: '',
            description: '',
            publish_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        })
        const commonFormRules = ref<FormRules<typeof commonFormModel>>({
            title: [
                {required: true, message: '请输入公告标题', trigger: 'blur'},
            ],
            description: [
                {required: true, message: '请输入公告内容', trigger: 'blur'},
            ],
            publish_time: [
                {required: true, message: '请输入发布时间', trigger: 'blur'},
            ]
        })

        const updateTime = ref('')
        const rawData = ref({})

        const getNoticeList = async () => {
            isLoading.value = true

            const res = await service.get("/noticeList")
            if (res.data.status === 200) {
                noticeList.value = res.data.data

                isLoading.value = false

                const maxIndexById = noticeList.value.reduce((prev, current) => (prev.id > current.id) ? prev.id : current.id)
                localStorage.setItem('noticeMaxIndex', JSON.stringify(maxIndexById))
            }
        }

        // 新增
        const openAddFormDialog = () => {
            commonFormModel.value = {
                title: '',
                description: '',
                publish_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            }
            addFormDialogRef.value.openDialog()
        }
        const closeAddFormDialog = () => addFormDialogRef.value.closeDialog()
        const handleAddNoticeSubmit = (FormEl: FormInstance | undefined) => {
            if (!FormEl) return;
            FormEl.validate(async (valid: boolean) => {
                if (!valid) return;
                else {
                    const maxIndex = JSON.parse(localStorage.getItem('noticeMaxIndex') || 0)
                    const newNoticeData = {
                        id: maxIndex + 1,
                        update_time: Random.now('A HH:mm:ss'),
                        ...commonFormModel.value,
                    }

                    addFormDialogRef.value.showLoading()

                    const res = await service.request({
                        url: '/addNotice',
                        method: 'POST',
                        data: newNoticeData
                    })
                    if (res.status === 200) {

                        closeAddFormDialog()

                        await getNoticeList()

                        toast(res.data.message)

                        FormEl.resetFields()
                    } else {
                        toast(res.data.message, 'error')
                    }
                }
            }).finally(() => {
                addFormDialogRef.value.hideLoading()
            })
        }

        // 编辑
        const openEditFormDialog = (row) => {
            editFormDialogRef.value.openDialog()

            commonFormModel.value = {...row}

            rawData.value = Object.assign({}, row)
        }
        const closeEditDialog = () => editFormDialogRef.value.closeDialog()
        const handleEditNoticeSubmit = (FormEl: FormInstance | undefined, editForm: typeof commonFormModel) => {
            if (!FormEl) return;
            FormEl.validate(async (valid: boolean) => {
                if (!valid) return;
                else {
                    // 没有编辑数据
                    const unChange = Object.is(JSON.stringify(rawData.value), JSON.stringify(editForm))
                    if (unChange) {
                        toast('数据未改动', 'info')

                        closeEditDialog()

                        return;
                    }
                    editFormDialogRef.value.showLoading()

                    // 每次提交编辑结果前 修改更新时间
                    updateTime.value = Random.now('A HH:mm:ss')
                    editForm.update_time = updateTime.value

                    const res = await service.request({
                        url: `/updateNotice/${editForm.id}`,
                        method: "PUT",
                        data: {
                            ...commonFormModel.value
                        }
                    })
                    if (res.data.status === 200) {
                        closeEditDialog()

                        await getNoticeList()

                        toast(res.data.message)
                    } else {
                        closeEditDialog()
                    }
                }
            }).finally(() => {
                editFormDialogRef.value.hideLoading()
            })
        }
        // 触发关闭表单后 清除表单校验
        const handleClosedDialog = (FormEl: FormInstance | undefined) => FormEl?.clearValidate()

        //删除
        const handleDeleteNotice = (id) => {
            showModal('确认删除该公告', '温馨提示', "warning", "", true, true)
                .then(async () => {
                    const res = await service.request({
                        url: `/deleteNotice/${id}`,
                        method: "DELETE",
                    })
                    if (res.status === 200) {
                        await getNoticeList()
                        toast(res.data.message)
                    }
                })
        }

        // 分页
        const handlePageChange = (newPage: number) => {

            currentPage.value = newPage

            // 根据起始索引 和 结束索引获取当前页的数据                  [0, 9]     [10, 19]   [20, 29] ...
            const initIndex = pageSize * (newPage - 1) // 10 * (1-1) 10 * (2-1) 10 * (3-1) ...
            const endIndex = pageSize * newPage //        10 * 1      10 * 2     10 * 3 ...
            // 存放当前页的数据
            const CurrentPageData = []
            for (let i = initIndex; i < endIndex; i++) {
                if (noticeList.value[i]) CurrentPageData.push(noticeList.value[i])
            }
            currentTableData.value = CurrentPageData
        }
        watch(noticeList, (newVal) => {
            currentPage.value = 1

            totalCount.value = newVal.length

            currentTableData.value = noticeList.value.filter((_, index) => index < pageSize)
        })

        return {
            noticeList,
            isLoading,
            getNoticeList,
            handleClosedDialog,
            // 新增
            addFormDialogRef,
            addFormModelRef,
            openAddFormDialog,
            handleAddNoticeSubmit,
            //
            commonFormModel,
            commonFormRules,
            // 编辑
            editFormDialogRef,
            editFormModelRef,
            openEditFormDialog,
            handleEditNoticeSubmit,

            // 删除
            handleDeleteNotice,
            // 分页
            pageSize,
            currentPage,
            totalCount,
            currentTableData,
            handlePageChange,

        }
    },
    {
        persist: {
            storage: sessionStorage,
        }
    }
)